package com.ruanjian2001.util;


import java.sql.*;
import java.util.ResourceBundle;

    /**
     * 数据库工具类
     */
public class JDBCUtil {
    private static ResourceBundle bundle = ResourceBundle.getBundle("resources/jdbc");
    private static String driver = bundle.getString("driver");

    private JDBCUtil(){

    }

    //注册驱动
    static {
        try {
            Class.forName(driver);
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * @return 数据库连接对象
     * @throws SQLException SQL异常
     */
    public static Connection getConnection() throws SQLException {

        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");
        Connection conn = DriverManager.getConnection(url,user,password);
        return conn;
    }

    /**
     * 关闭资源
     * @param conn 数据库连接对象
     * @param stmt 数据库操作对象
     * @param rs 结果集
     */
    public static void close(Connection conn, PreparedStatement stmt, ResultSet rs){
        if(conn != null) {
            try {
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try{
                stmt.close();
            }catch(SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs != null){
            try{
                rs.close();
            }catch(SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭资源
     * @param conn 数据库连接对象
     * @param stmt 数据库操作对象
     * @param rs 结果集
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs){
        if(conn != null) {
            try {
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try{
                stmt.close();
            }catch(SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs != null){
            try{
                rs.close();
            }catch(SQLException e) {
                e.printStackTrace();
            }
        }
    }



}
